package com.weblog.weblog.jwt.config;

import com.weblog.weblog.jwt.filter.JwtAuthenticationFilter;
import com.weblog.weblog.jwt.handler.RestAuthenticationFailureHandler;
import com.weblog.weblog.jwt.handler.RestAuthenticationSuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 认证功能配置
 * @author gc
 * @class_name JwtAuthenticationSecurityConfig
 * @date 2023年09月15日 20:52
 */
@Configuration
public class JwtAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {


    private final RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;

    private final RestAuthenticationFailureHandler restAuthenticationFailureHandler;

    private final PasswordEncoder passwordEncoder;

    private final UserDetailsService userDetailsService;

    public JwtAuthenticationSecurityConfig(RestAuthenticationSuccessHandler restAuthenticationSuccessHandler, RestAuthenticationFailureHandler restAuthenticationFailureHandler, PasswordEncoder passwordEncoder, UserDetailsService userDetailsService) {
        this.restAuthenticationSuccessHandler = restAuthenticationSuccessHandler;
        this.restAuthenticationFailureHandler = restAuthenticationFailureHandler;
        this.passwordEncoder = passwordEncoder;
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void configure(HttpSecurity httpSecurity) {
        //自定义用于JWT身份验证过滤器
        JwtAuthenticationFilter filter = new JwtAuthenticationFilter();
        filter.setAuthenticationManager(httpSecurity.getSharedObject(AuthenticationManager.class));

        //设置登录认证对应处理类
        filter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);
        filter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);

        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();

        provider.setUserDetailsService(userDetailsService);

        //设置加密算法
        provider.setPasswordEncoder(passwordEncoder);
        httpSecurity.authenticationProvider(provider);

        httpSecurity.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);

    }
}
